package top.chengdongqing.mishop.product.review

import org.springframework.cache.annotation.Cacheable
import org.springframework.data.domain.Pageable
import org.springframework.stereotype.Service
import top.chengdongqing.mishop.common.pageable.Page1
import top.chengdongqing.mishop.product.review.vo.ProductReviewStatisticsVO
import top.chengdongqing.mishop.product.review.vo.ProductReviewVO
import top.chengdongqing.mishop.repositories.ProductReviewRepository
import java.math.BigDecimal
import java.math.RoundingMode

@Service
class ProductReviewService(private val reviewRepository: ProductReviewRepository) {

    @Cacheable(value = ["products:reviews:statistics"], key = "#productId")
    fun statistics(productId: Int): ProductReviewStatisticsVO {
        // 评论总数
        val allCount = reviewRepository.countByProductId(productId)
        // 好评数量
        val satisfiedCount = reviewRepository.countByProductIdAndRatingGreaterThanEqual(productId, 3)
        // 满意度
        val satisfaction = allCount.takeUnless { it > 0 } ?: BigDecimal(satisfiedCount)
            .divide(BigDecimal(allCount), 4, RoundingMode.FLOOR)
            .multiply(BigDecimal(100))
        // 每种评分的数量
        val scoresMap = reviewRepository.countByProductIdGroupByScore(productId).associate { it[0] to it[1] }

        return ProductReviewStatisticsVO(
            allCount,
            satisfiedCount,
            satisfaction.toDouble(),
            scoresMap
        )
    }

    fun findAllByPage(
        productId: Int,
        rating: Int?,
        withPhotosOnly: Boolean?,
        pageable: Pageable
    ): Page1<ProductReviewVO> {
        val page = reviewRepository.findAllByPage(productId, rating, withPhotosOnly, pageable)
            .map { ProductReviewVO.of(it) }
        return Page1.of(page)
    }
}